package com.comp490.shooter;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.comp490.input.TouchController;
import com.comp490.navigation.MainMenu;
import com.comp490.sound.SoundManager;

public class MainActivity extends Activity implements OnClickListener,
		AnimationListener
{
	private GameView gameView;
	private View scoreView;
	private TouchController touchController;
	private TextView scoreTitle, score;
	private Button nextLevel, mainMenu;
	private boolean pauseMenuShowing;
	private long scorePool;
	private Timer t; // used for animating score menu
	char[] scoreText  = new char[]{'S','c','o','r','e',':',' ','0','0','0','0','0','0','0','0','0','0'};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		hideNavButtons();
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_main);

		// Set the hardware buttons to control the music
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		playMusic();
		gameView = (GameView) findViewById(R.id.game_view);
		scoreView = (View) findViewById(R.id.content);
		scoreView.setVisibility(View.GONE);
		scoreTitle = (TextView) findViewById(R.id.score_title);
		scoreTitle.setTypeface(Typeface.createFromAsset(gameView.getContext()
				.getAssets(), "photonica_regular.ttf"));
		score = (TextView) findViewById(R.id.score_list);
		score.setTypeface(Typeface.createFromAsset(gameView.getContext()
				.getAssets(), "arkitect_round.ttf"));
		nextLevel = (Button) findViewById(R.id.next_level);
		mainMenu = (Button) findViewById(R.id.return_main_menu);
		nextLevel.setTypeface(Typeface.createFromAsset(gameView.getContext()
				.getAssets(), "arkitect_round.ttf"));
		mainMenu.setTypeface(Typeface.createFromAsset(gameView.getContext()
				.getAssets(), "arkitect_round.ttf"));
		nextLevel.setOnClickListener(this);
		mainMenu.setOnClickListener(this);
		touchController = new TouchController();
		gameView.setOnTouchListener(touchController);
		gameView.setTouchController(touchController);
		pauseMenuShowing = false;
		ImageView pause = (ImageView) findViewById(R.id.pause_button);
		pause.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				SoundManager.playSoundEfx(SoundManager.BUTTON_CLICK);
				pauseGame();
			}
		});
	}

	public void reduceLifeUI(int life)
	{
		switch (life)
		{
			case 1:
				((ImageView) findViewById(R.id.one_life))
						.setVisibility(View.GONE);
				break;

			case 2:
				((ImageView) findViewById(R.id.second_life))
						.setVisibility(View.GONE);
				break;

			case 3:
				((ImageView) findViewById(R.id.three_life))
						.setVisibility(View.GONE);
				break;
		}
	}

	public void resetLifeUI()
	{
		((ImageView) findViewById(R.id.one_life)).setVisibility(View.VISIBLE);
		((ImageView) findViewById(R.id.second_life)).setVisibility(View.VISIBLE);
		((ImageView) findViewById(R.id.three_life)).setVisibility(View.VISIBLE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();

		if (!pauseMenuShowing)
			showPauseMenu();
	}

	@Override
	protected void onPause()
	{
		// should save the state of the GameView here for when activity loses
		// focus
		gameView.pause();
		pauseMusic();
		super.onPause();
	}

	@Override
	public void onBackPressed()
	{
		pauseGame();
	}

	private void pauseGame()
	{
		if (scoreView.isShown())
			return;

		SoundManager.playSoundEfx(SoundManager.BUTTON_CLICK);
		gameView.pause();
		pauseMusic();

		if (!pauseMenuShowing)
			showPauseMenu();
	}

	private void playMusic()
	{
		SoundManager.getInstance(MainActivity.this);
		SoundManager.playBackgroundMusic(SoundManager.LEVEL_ONE_BG);
	}

	private void pauseMusic()
	{
		SoundManager.getInstance(MainActivity.this);
		SoundManager.pauseBackgroundMusic();
	}

	private void resumeMusic()
	{
		SoundManager.getInstance(MainActivity.this);
		SoundManager.resumeBackgroundMusic();
	}

	public void showScoreMenu(final boolean levelCompleted)
	{
		if (scoreView.isShown()
				|| (scoreView.getAnimation() != null && (scoreView
						.getAnimation().isInitialized() || scoreView
						.getAnimation().hasStarted())))
			return;
		System.out.println("ITS OVER!!!");
		pauseMusic();
		SoundManager.playBackgroundMusic(SoundManager.SCORE_BG);
		for(int i = 1; i < 10; i++)
		{
			scoreText[scoreText.length - i] = '0';
		}
		
		runOnUiThread(new Runnable()
		{
			public void run()
			{
				scoreView.setAnimation(AnimationUtils.loadAnimation(
						MainActivity.this, android.R.anim.slide_in_left));
				scoreView.getAnimation()
						.setAnimationListener(MainActivity.this);
				scoreTitle.setText(levelCompleted ? "Level Completed!"
						: "Game Over!");
				score.setText(scoreText, 0, scoreText.length);
				nextLevel.setText(levelCompleted ? "Next Level"
						: "Restart Level");
				nextLevel.setVisibility(View.GONE);
				mainMenu.setVisibility(View.GONE);
				scoreView.setVisibility(View.VISIBLE);
			}
		});
	}

	/** Hide the navigation buttons for devices running API 11 and above */
	@TargetApi(11)
	private void hideNavButtons()
	{
		if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 11)
		{
			getWindow().getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LOW_PROFILE);
		}
	}

	/** build a new pause menu dialog and then display it */
	private void showPauseMenu()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setIcon(R.drawable.spaceship_tiny);
		builder.setTitle("Paused!");
		builder.setCancelable(false); // prevents user from accidentally
										// resuming

		builder.setPositiveButton("Resume",
				new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						SoundManager.playSoundEfx(SoundManager.BUTTON_CLICK);
						gameView.resumeWorkerBee();
						resumeMusic();
						hideNavButtons();
						pauseMenuShowing = false;
					}
				});

		builder.setNegativeButton("Return to Main Menu",
				new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						pauseMenuShowing = true;
						SoundManager.playSoundEfx(SoundManager.BUTTON_CLICK);
						startActivity(new Intent(MainActivity.this,
								MainMenu.class));
						finish();
					}
				});

		// builder.setOnCancelListener(new DialogInterface.OnCancelListener()
		// {
		// public void onCancel(DialogInterface dialog)
		// {
		// gameView.resumeWorkerBee();
		// resumeMusic();
		// hideNavButtons();
		// pauseMenuShowing = false;
		// }
		// });

		builder.create().show();
		pauseMenuShowing = true;
	}

	public void onClick(View v)
	{
		SoundManager.playSoundEfx(SoundManager.BUTTON_CLICK);
		switch (v.getId())
		{
			case R.id.next_level:
				if ("restart level".equalsIgnoreCase(nextLevel.getText()
						.toString()))
				{
					pauseMusic();
					playMusic();
					gameView.resetGame();
				}
				else
				{
					// Next level
				}
				scoreView.setAnimation(AnimationUtils.loadAnimation(this,
						android.R.anim.slide_out_right));
				scoreView.setVisibility(View.GONE);
				break;
			case R.id.return_main_menu:
				pauseMusic();
				startActivity(new Intent(MainActivity.this, MainMenu.class));
				finish();
				break;
		}
	}

	public int isHighScore(int level, long score)
	{
		List<ScoreStruct> scores = ScoreConduit.readHighScores(this, level);
		for (int i = 0; i < scores.size(); i++)
		{
			if (scores.get(i).getScore() < score)
			{
				return i;
			}
		}
		return -1;
	}

	public void onAnimationStart(Animation animation)
	{

	}

	public void onAnimationEnd(Animation animation)
	{
		final long gameScore = gameView.getScore();
		
		scorePool = 0;
		final int inc = (int) gameScore / 300;
		final Runnable animator = new Runnable()
		{
			
			long scoreTemp;
			@Override
			public void run()
			{
				if (scorePool >= gameScore)
				{
					// to ensure only processes once while timer task
					// stops
					if (nextLevel.isShown() && mainMenu.isShown())
						return;

					nextLevel.setVisibility(View.VISIBLE);
					mainMenu.setVisibility(View.VISIBLE);
					int place = isHighScore(1, gameScore);
					if (place != -1)
						showNewHighScoreEntry(gameScore, place, 1);
					
					scoreTemp = gameScore;
					for(int i = 1; i < 10; i++)
					{
						scoreText[scoreText.length - i] = (char)('0' + scoreTemp % 10);
						scoreTemp /=10;
					}
					
					score.setText(scoreText, 0, scoreText.length);
					t.cancel();
					t.purge();
					return;
				}

				SoundManager.playSoundEfx(SoundManager.SCORE_BEEP);
				scorePool += inc;
				scoreTemp = scorePool;
				for(int i = 1; i < 10; i++)
				{
					scoreText[scoreText.length - i] = (char)('0' + scoreTemp % 10);
					scoreTemp /=10;
				}
				score.setText(scoreText, 0, scoreText.length);
				
			}
		};
		t = new Timer();
		t.schedule(new TimerTask()
		{
			public void run()
			{
				runOnUiThread(animator);
			}
		}, 0, 10);
	}

	public void onAnimationRepeat(Animation animation)
	{

	}

	private Dialog builder = null;

	public void showNewHighScoreEntry(final long score, final int place,
			final int level)
	{
		if (builder == null)
		{
			builder = new Dialog(MainActivity.this,
					android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
			builder.setContentView(R.layout.score_entry_layout);
			TextView text = (TextView) builder
					.findViewById(R.id.score_entry_title);
			text.setTypeface(Typeface.createFromAsset(gameView.getContext()
					.getAssets(), "photonica_regular.ttf"));

			text = (TextView) builder.findViewById(R.id.score_qty);
			text.setTypeface(Typeface.createFromAsset(gameView.getContext()
					.getAssets(), "photonica_regular.ttf"));

			final EditText editText = (EditText) builder
					.findViewById(R.id.score_entry);
			editText.setTypeface(Typeface.createFromAsset(gameView.getContext()
					.getAssets(), "arkitect_round.ttf"));
			Button cancel = (Button) builder.findViewById(R.id.cancel);
			Button submit = (Button) builder.findViewById(R.id.submit);
			cancel.setTypeface(Typeface.createFromAsset(gameView.getContext()
					.getAssets(), "arkitect_round.ttf"));
			submit.setTypeface(Typeface.createFromAsset(gameView.getContext()
					.getAssets(), "arkitect_round.ttf"));

			submit.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					if (editText.getText() == null)
						return;
					String scoreQty = editText.getText().toString();
					if (scoreQty.replaceAll(" ", "").length() != 0)
					{
						ScoreConduit.writeScores(MainActivity.this, scoreQty,
								score, place, level);
						editText.getText().clear();
						builder.dismiss();
					}
				}
			});

			cancel.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					builder.dismiss();
				}
			});
		}

		if (!builder.isShowing())
		{
			TextView text = (TextView) builder.findViewById(R.id.score_qty);
			text.setText(scoreText, 0 , scoreText.length);
			builder.show();
		}
	}

}